#!/bin/bash

INSTALLSTAGING=/tmp/flipinstall
TARGET_KEXT=/System/Library/Extensions
TARGET_FRAMEWORK=/Library/Frameworks
#INSTALLSTAGING=/Users/saustin/install
#TARGET_KEXT=/Users/saustin/install/test/Extensions
#TARGET_FRAMEWORK=/Users/saustin/install/test/Frameworks

function goto_os_dir {
	OSSTR=`sw_vers | awk '/ProductVersion:/ {print $2};' | sed 's/\(10\.[0-9]*\).*/\1/'`
	test -d $INSTALLSTAGING/$OSSTR
	if [ "$?" != "0" ]; then
		echo no install folder
		exit
	fi
	cd $INSTALLSTAGING/$OSSTR
}

function install_kext {
	KEXT=$1
	chown -R root:wheel $KEXT
	find $KEXT -type d -exec chmod 755 {} \;
	find $KEXT -type f -exec chmod 644 {} \;
	test -e $TARGET_KEXT/$KEXT
# FVSW-10115 There is a chance that the kext already exists because it is not removed
# as part of uninstall.  Therefore, do not remove the existing kext, just use it.
# This fix works for now, but will need to be revised if we upgrade the kext in the future
#		kextunload $TARGET_KEXT/$KEXT
#		rm -rf $TARGET_KEXT/$KEXT
	if [ "$?" != "0" ]; then
		mv $KEXT $TARGET_KEXT/$KEXT
	fi
}

function install_framework {
	FRAMEWORK=$1
	chown -R root:wheel $FRAMEWORK
	find $FRAMEWORK -type d -exec chmod 755 {} \;
	find $FRAMEWORK -type f -exec chmod 644 {} \;
	test -e $TARGET_FRAMEWORK/$FRAMEWORK
	if [ "$?" == "0" ]; then
		rm -rf $TARGET_FRAMEWORK/$FRAMEWORK
	fi
	mv $FRAMEWORK $TARGET_FRAMEWORK/$FRAMEWORK
}

function clean_up_install {
	echo cleaning up
	cd $INSTALLSTAGING/..
	rm -rf $INSTALLSTAGING
}


cd $INSTALLSTAGING

goto_os_dir

test -d kext
if [ "$?" == "0" ]; then
	cd kext
	for ext in `ls -d [A-Za-z]*` ;
	do
		install_kext $ext
	done
	cd ..
fi

test -d framework
if [ "$?" == "0" ]; then
	cd framework
	for frm in `ls -d [A-Za-z]*` ;
	do
		install_framework $frm
	done
	cd ..
fi

test -d support
echo looking for support
if [ "$?" == "0" ]; then
	echo found
	cd support
	DESTCONFIG=/Library/Application\ Support/Flip\ Video/FlipShareConfig
	cp FlipShareConfig "$DESTCONFIG"
	chown root:wheel "$DESTCONFIG"
	chmod 755 "$DESTCONFIG"
	chmod +s "$DESTCONFIG"
	cd ..
fi
echo done

test -d startup
if [ "$?" == "0" ]; then
	cd startup
	for item in `ls -d [A-Za-z]*` ;
	do
		cp -r "$item" /System/Library/StartupItems
		STARTDIR="/System/Library/StartupItems/$item"
		chown -R root:wheel "$STARTDIR"
		chmod -R 755 "$STARTDIR"
		"/System/Library/StartupItems/$item/$item"
	done
	cd ..
fi

clean_up_install

# signal kextd to update kext cache
touch $TARGET_KEXT
KEXTDPID=`ps -ax | awk '{print $1" "$5}' | grep kextd | awk '{print $1}'`
if [ "$KEXTDPID" != "" ]; then
	/bin/kill -1 $KEXTDPID
fi
echo kernel components installed
